package com.motu.vertx.module.utility.webhandler;


import com.motu.vertx.module.utility.mysql.MysqlTool;
import com.motu.vertx.module.utility.redis.RedisTools;
import com.motu.vertx.module.utility.toolset.TimeUtils;
import com.motu.vertx.module.utility.toolset.Tool;
import com.motu.vertx.module.utility.webtool.BaseWebHandler;
import io.vertx.core.Future;
import io.vertx.core.http.HttpServerResponse;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
//import io.vertx.ext.sync.Sync;
import io.vertx.ext.web.RoutingContext;
import io.vertx.ext.web.client.WebClient;
import io.vertx.sqlclient.Pool;
import io.vertx.redis.client.RedisAPI;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Iterator;
import java.util.Map;

public class RedistoolHandler extends BaseWebHandler{
	private final static Logger logger = LoggerFactory.getLogger(RedistoolHandler.class);

	private static Pool sqlClientGame = null;
	private static RedisAPI redisClient = null ;

	public static void init(Pool clientGame,RedisAPI redisClientTmp){
		sqlClientGame = clientGame;
		redisClient = redisClientTmp;
	}

	public static void redisCheckBySql(RoutingContext routingContext,JsonObject json,String adminName,WebClient client){
		HttpServerResponse response = routingContext.response();
		logger.info("redisCheckBySql start !!!");
		String tableName = json.getString("table");
		int num = json.getInteger("num");
		JsonArray ignoreKeyArray = new JsonArray();
		if (json.containsKey("ignoreKeys")) {
			String[] ignoreKeys = json.getString("ignoreKeys").split(";");
			for (int i = 0 ; i < ignoreKeys.length; i++) {
				ignoreKeyArray.add(ignoreKeys[i]);
			}
		}


		long curtime = TimeUtils.getCurTime();
		JsonObject result = new JsonObject();
		JsonArray differenceList = new JsonArray();
		//取最后登录时间在 2小时之前 24小时之内的数据
		String userListRandSql = "select id from userinfo where logintime >= " + (curtime -  24 * 60 * 60) + " and logintime <= " + (curtime -  22 * 60 * 60) + "  order by rand() limit " + num;
		Future<JsonArray> userListRandFuture = MysqlTool.queryJsonArrayFromDb(sqlClientGame, userListRandSql, new JsonArray());
		JsonArray userIdList = Future.await(userListRandFuture);
		result.put("userNum",userIdList.size());
		int passNum = 0;
		for ( int i = 0; i < userIdList.size(); i++) {
			long userId = userIdList.getJsonObject(i).getLong("id");
			String redisKey = tableName + "." + userId;
			Future<JsonObject> userInfoByRedisFuture = RedisTools.getHashJsonObject(redisKey);
			JsonObject userInfoByRedis = Future.await(userInfoByRedisFuture);
			//获取最大分组
			String userSql = "select * from " + tableName + " where id=" + userId;
			Future<JsonObject> userInfoFuture = MysqlTool.queryJsonObjectFromDb(sqlClientGame, userSql, new JsonArray());
			JsonObject userInfoBySql = Future.await(userInfoFuture);
			if (checkData(userId,userInfoByRedis,userInfoBySql,differenceList,ignoreKeyArray)) {
				passNum++;
			}
		}
		result.put("passNum",passNum);
		result.put("differenceList",differenceList);
		sendHttpResponse(response, new JsonObject().put("data", result));
	}

	/**
	 * 校验redis数据和sql数据
	 * @param redisData
	 * @param sqlData
	 * @param differenceList
	 * @return
	 */
	public static Boolean checkData(long userId,JsonObject redisData, JsonObject sqlData,JsonArray differenceList,JsonArray ignoreKeyArray){
		Boolean isSame = true;
		Iterator iter = sqlData.iterator();
		while (iter.hasNext()) {
			Map.Entry entry = (Map.Entry) iter.next();
			String key = entry.getKey().toString();
			if (!ignoreKeyArray.contains(key)) {
				String sqlValue = entry.getValue().toString();
				if (redisData.getValue(key) != null) {
					String redisValue = redisData.getValue(key).toString();
					if (!sqlValue.equals(redisValue)) {
						isSame = false;
						JsonObject difference = new JsonObject();
						difference.put("id",userId);
						difference.put("redis",redisData);
						difference.put("sql",sqlData);
						differenceList.add(difference);
						break;
					}
				}
			}

		}
		return isSame;
	}
}
